import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_quill/flutter_quill.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:lifecycle/lifecycle.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:smart_translator/app/services/AudioService.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import 'app/routes/app_pages.dart';
import 'app/services/DbService.dart';
import 'app/storage/StorageManager.dart';
import 'app/style/widget_style.dart';
import 'app/widgets/TranslationOverLay3.dart';

void main() async {

  // WidgetsFlutterBinding.ensureInitialized();
  initAmp();

}

void initAmp() {
  final UmengApmSdk umengApmSdk = UmengApmSdk(
    name: '',
    bver: '',
    // 是否开启SDK运行时日志输出
    enableLog: true,
    // 您使用的flutter版本，默认为空，为方便定位访问，建议配置
    flutterVersion: '3.32.3',
    engineVersion: 'cf56914b32',

    // 开启监测页面帧率（默认关闭) 版本 v2.1.3 可支持
    enableTrackingPageFps: true,

    // 开启监测页面性能（默认关闭）版本 v2.1.3 可支持
    enableTrackingPagePerf: true,

    // 带入继承ApmWidgetsFlutterBinding的覆写和初始化方法, 可用于自定义监听应用生命周期
    // 确保去掉原有的WidgetsFlutterBinding.ensureInitialized() ，以免出现重复初始化绑定的异常造成无法正常初始化，SDK内部已通过initFlutterBinding入参带入继承的WidgetsFlutterBinding实现初始化操作
    initFlutterBinding: MyApmWidgetsFlutterBinding.ensureInitialized,
    // 抛出异常事件
    onError: (exception, stack) {
      print(exception);
    },

  );
  umengApmSdk.init(appRunner: (observer) async {
    // 确保去掉原有的WidgetsFlutterBinding.ensureInitialized() ，以免出现重复初始化绑定的异常造成无法正常初始化，SDK内部已通过initFlutterBinding入参带入继承的WidgetsFlutterBinding实现初始化操作
    // 依赖ensureInitialized()初始化的代码可在此调用
    // 需要异步获取设置应用名称和版本号可在此回调中操作
    // SDK实例化的设置可先将name和bver 为 "",然后通过以下方式进行设置
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String packageName = packageInfo.packageName;
    String buildNumber = packageInfo.buildNumber;
    String version = packageInfo.version;
    umengApmSdk.name = packageName;
    umengApmSdk.bver = '$version+$buildNumber';

    initYouMeng();

    StorageManager.initStorage();

    initServices();
    await ScreenUtil.ensureScreenSize();

    configLoading();

    WidgetsFlutterBinding.ensureInitialized();

    return MyApp(observer);
  });
}

void initYouMeng() {
  UmengCommonSdk.initCommon('686b3118bc47b67d83a4f4f1', '686b336b79267e0210a2acba', 'self-chinnel');
  UmengCommonSdk.setPageCollectionModeManual();
}

void initServices() async {
  print('starting services ...');
  /// Here is where you put get_storage, hive, shared_pref initialization.
  /// or moor connection, or whatever that's async.
  Get.put(await DbService().init());
  //audio 服务管理.
  Get.put(AudioService().init());
  print('All services started..');


}


@pragma("vm:entry-point")
void overlayMain() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(
    MaterialApp(
      color:Colors.transparent,
      debugShowCheckedModeBanner: false,
      home: Material(
        color:Colors.transparent,
       child: TranslationOverLay3(),
      ),
    ),
  );
}



class MyApp extends StatelessWidget {

  MyApp([this._navigatorObserver]);

  NavigatorObserver? _navigatorObserver;

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, designSize: const Size(375, 812));

    return GetMaterialApp(
      title: "智译",
      initialRoute: AppPages.INITIAL,
      getPages: AppPages.routes,
      builder: EasyLoading.init(),
      theme: AppStyleThemeData.CustomThemeLight,
      navigatorObservers: <NavigatorObserver>[defaultLifecycleObserver,
        _navigatorObserver ?? ApmNavigatorObserver.singleInstance],
      localizationsDelegates: [ FlutterQuillLocalizations.delegate,],
    );
  }
}


void configLoading() {
  EasyLoading.instance
    ..displayDuration = const Duration(milliseconds: 2000)
    ..indicatorType = EasyLoadingIndicatorType.fadingCircle
    ..loadingStyle = EasyLoadingStyle.dark
    ..indicatorSize = 45.0
    ..radius = 10.0
    ..progressColor = Colors.yellow
    ..backgroundColor = Colors.green
    ..indicatorColor = Colors.yellow
    ..textColor = Colors.yellow
    ..maskColor = Colors.blue.withValues(alpha: 0.5)
    ..userInteractions = true
    ..dismissOnTap = false;
}


class MyApmWidgetsFlutterBinding extends ApmWidgetsFlutterBinding {
  @override
  void handleAppLifecycleStateChanged(AppLifecycleState state) {
    // 添加自己的实现逻辑
    print('AppLifecycleState changed to $state');
    super.handleAppLifecycleStateChanged(state);
  }

  static WidgetsBinding? ensureInitialized() {
    MyApmWidgetsFlutterBinding();
    return WidgetsBinding.instance;
  }
}


